package com.rumo.demo;
 
import java.util.HashMap;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSONObject;
import com.rumo.util.HttpUtils;

@ServerEndpoint("/websocket/{userId}")
public class SocketServer {
 
	private static Map<String, Session> sessionMap=new HashMap<String, Session>();//在线的客户端session集合，只在第一次new的时候初始化。
	private static String AUTO_CHAT_URL = "http://api.qingyunke.com/api.php";// 机器人接口,from 青云客 www.qingyunke.com
	private static String BEGIN = "SocketBegin";
	private static String TYPE = "sendToServer";
	
  /**
   * 接收信息事件
   * @param message 客户端发来的消息
   * @param session 当前会话
   */
  @OnMessage
  public void onMessage(String message,Session session,@PathParam(value="userId")String userId)throws Exception {
   
    try {
    	//循环给每个客户端发送信息
    	/*Iterator<String> it = sessionMap.keySet().iterator();
    	while(it.hasNext()){
    		String key = (String) it.next();
    		Session value = sessionMap.get(key);
    		value.getBasicRemote().sendText(message);
    	}*/
    	 System.out.println("用户"+userId+"说："+message+"。");
    	 String reply = autoChat(resolveMsg(message));
    	 if(!BEGIN.equals(reply)){
    		 System.out.println("机器人回复： " + reply);
    		 session.getBasicRemote().sendText(reply);
    	 }
    	 System.out.println("当前在线人数："+sessionMap.size());
	} catch (Exception e) {
		System.out.println("接收消息事件异常!");
	}
  }
  
  /**
   * 打开连接事件
 * @throws Exception 
   */
  @OnOpen
  public void onOpen(Session session,@PathParam(value="userId")String userId) throws Exception {
    System.out.println("打开连接成功！");
    sessionMap.put(userId, session);
    System.out.println("用户"+userId+"进来了。。。");
    System.out.println("当前在线人数："+sessionMap.size());
  }
 
  /**
   * 关闭连接事件
   */
  @OnClose
  public void onClose(Session session,@PathParam(value="userId")String userId) {
    System.out.println("关闭连接成功！");
    System.out.println("用户"+userId+"离开了。。。");
    sessionMap.remove(userId);
    System.out.println("当前在线人数："+sessionMap.size());
  }
  
  /**
   * 错误信息响应事件
   * @param session
   * @param throwable
   */
  @OnError
  public void OnError(Session session,Throwable throwable,@PathParam(value="userId")String userId) {
	    System.out.println("异常："+throwable.getMessage());
	    System.out.println("用户"+userId+"的连接出现了错误。。。");
	    System.out.println("当前在线人数："+sessionMap.size());
  }
  
  public String autoChat(String msg){
	  if(BEGIN.equals(msg)){
		  return BEGIN;
	  }
	  Map<String, String> parameters = new HashMap<String, String>();  
      parameters.put("key", "free");
      parameters.put("appid", "0");
      parameters.put("msg", msg);
      return getContent(HttpUtils.sendGet(AUTO_CHAT_URL, parameters));
  }
  
  public String resolveMsg(String msg){
	  if(BEGIN.equals(msg)){
		  return BEGIN;
	  }
	  JSONObject resultJson = JSONObject.parseObject(msg);
  	  String type = (String) resultJson.get("type");
  	  String result = "糟糕，消息不小心丢了~";
  	  if(TYPE.equals(type)){
  		result = (String) resultJson.get("data");
  	  }
  	  return result;
  }
  
  /**
   * 从机器人接口中解析对话内容
   * @param resultStr
   * @return
   */
  public String getContent(String resultStr){
  	JSONObject resultJson = JSONObject.parseObject(resultStr);
  	int result = new Integer(1);
  	result = (Integer) resultJson.get("result");
  	if(result==0){
  		return (String) resultJson.get("content");
  	}
      return "糟糕，消息不小心丢了~";
  }
  
}